/**
 * Basic Shell Passthrough Interface
 * Author: Garrett Sparks
 *
 */

#include <stdio.h>
#include <unistd.h>
#include <string.h>



#define MAX_LINE 80 /* 80 chars per line, per command */
#define COMPARE_SUB 4

int main(void)
{
    int should_run = 1;

    do {
        char keyboard_input[MAX_LINE];
    	char *args[MAX_LINE];	/* command line (of 80) has max of 40 arguments */
        char *token;
        int count = 0, i, should_wait = 1;
        pid_t new_pid;

        printf("gshell>");
        fflush(stdout);  
        /* Get keyboard input from stdin */ 
        fgets(keyboard_input, sizeof keyboard_input, stdin);
        /* Prevent segfault on just 'Enter' key being pressed */
        if(strncmp(keyboard_input, "\n", COMPARE_SUB) != 0) {
            keyboard_input[strlen(keyboard_input)-1] = '\0';
            /* Check for 'exit' commands */
            if(strncmp(keyboard_input, "EXIT", COMPARE_SUB) != 0 && 
                strncmp(keyboard_input, "exit", COMPARE_SUB) != 0 && 
                strncmp(keyboard_input, "Exit", COMPARE_SUB) != 0) {
                /* Tokenize on SPACE and create array with arguments */
                token = strtok(keyboard_input, " ");
                while (token != NULL) {
                    args[count] = token;
                    count++;
                    token = strtok(NULL, " ");
                }
                args[count] = '\0';
                if (*args[count - 1] == '&') {
                    args[count - 1] = '\0';
                    should_wait = 0;
                }

                new_pid = fork();
                if (new_pid < 0) {
                    fprintf(stderr, "Fork Failed");
                    return 1;
                } else if(new_pid == 0) {
                    execvp(*args, args);
                } else {
                    if (should_wait) {
                        wait(NULL);
                    }
                }
            } else {
                should_run = 0;
            }
        }
    } while(should_run);
    
	return 0;
}
